#!/usr/bin/env python
# -*- coding: utf-8 -*-
__Author__ = "YINGHAI"
__Email__ = "pyj2897022134@gmail.com"

from flask import Flask, jsonify
from flask_cors import CORS
from flask import Flask, url_for, redirect, flash
from flask import render_template, request
from datetime import timedelta

from db import dbconnect
import reconfig

app = Flask(__name__)
CORS(app)

# -------------配置文件-----------
app.config['SECRET_KEY'] = '123456'
app.config['SEND_FILE_MAX_AGE_DEFAULT'] = timedelta(seconds=1)
app.config['PERMANENT_SESSION_LIFETIME'] = timedelta(seconds=1)
app.config['JSON_AS_ASCII'] = False
# -------------配置文件-----------


# -------------路由定位页面------------

@app.route('/index/<username>', methods=['GET','POST'])
def index(username):
    return render_template('index.html',user=username)

@app.route('/user_m', methods=['GET','POST'])
def user_m():
    if request.method == 'GET':
        return render_template('user_manage.html')
    elif request.method == 'POST':
        conn = reconfig.getconnect()
        res =dbconnect.getDataFromSQL(conn, 'users')
        conn.close()
        return jsonify({'data':res})


@app.route('/user_xg', methods=['GET', 'POST'])
def user_xg():
    if request.method == 'POST':
        conn = reconfig.getconnect()
        data = request.get_json()
        username = data['un_text']
        origine_pw = data['y_pw_text']
        new_pw = data['x_pw_text']
        print(username, origine_pw, new_pw)
        result = dbconnect.login(username, origine_pw, conn)
        if result > 0:
            origine_user_info = {'username': username, 'password': origine_pw}
            new_user_info = {'password': new_pw}
            dbconnect.update(origine_user_info, new_user_info, 'users', conn)
            print('yes')
            return jsonify({'data': 'success'})
        else:
            return jsonify({'data': 'error'})


@app.route('/user_sc', methods=['GET', 'POST'])
def user_sc():
    conn = reconfig.getconnect()
    data = request.get_json()
    for key, value in data.items():
        flag = dbconnect.delete(key, value, 'users', conn)
        if flag == 0:
            return jsonify({'data': 'success'})
        else:
            return jsonify({'data': 'error'})


@app.route('/Error', methods=['GET','POST'])
def Error():
    return render_template('error.html')

@app.route('/login', methods=['GET','POST'])
def login():
    if request.method == 'POST':
        data = request.get_json()
        u = data['username']
        p = data['password']

        conn = reconfig.getconnect()
        print('连接成功')
        cursor = conn.cursor()
        sql = "select * from users where username='%s'and password='%s'"
        data = (u, p)
        # 执行sql
        cursor.execute(sql % data)

        # 得到结果
        num = cursor.rowcount
        conn.close()
        print(num)
        if num > 0:
            return jsonify({'data':'success'})#redirect(url_for('index',username=u))
        else:
            return jsonify({'data':'error'})#redirect(url_for('Error'))
    return render_template('login.html')

@app.route('/register', methods=['GET','POST'])
def register():
    if request.method == 'POST':
        data = request.get_json()
        r_u = data['re_username']
        r_p = data['re_password']

        conn = reconfig.getconnect()
        cursor = conn.cursor()
        sql = "select * from users where username='%s'"
        # 执行sql
        cursor.execute(sql % r_u)
        num = cursor.rowcount

        if num == 0:
            l = []
            d = {'username':r_u,'password':r_p}
            l.append(d)
            flag = dbconnect.insert(l,'users',2,conn)
            conn.close()
            return jsonify({'data':'success'})

        else:
            conn.close()
            return jsonify({'data':'error'})  # redirect(url_for('Error'))

@app.route('/deletetr', methods=['GET','POST'])
def deletetr():
    if request.method == 'POST':
        conn = reconfig.getconnect()
        data = request.get_json()
        for key, value in data.items():
            flag = dbconnect.delete(key, value[1:], dbconnect.getTableName(value[0]), conn)
        if flag == 0:
            return jsonify({'data': 'success'})
        else:
            conn.close()
            return jsonify({'data': 'error'})  # redirect(url_for('Error'))


@app.route('/search', methods=['GET','POST'])
def search():
    data = request.get_json()
    url = data['url']
    if request.method == 'POST':
        conn = reconfig.getconnect()
        #从数据库提取数据
        #res = dbconnect.getDataFromSQL(conn, dbconnect.getTableName(url))
        #从网页爬取数据并存入数据库
        res = dbconnect.getData(url)
        conn.close()
        #print(res)
        return jsonify({'data': res})
    return redirect(url_for('ymzs',url=url))

@app.route('/ymzs/?<path:url>', methods=['GET','POST'])
def ymzs(url):
    if request.method == 'POST':
        data = request.get_json()
        url_s = data['url']
    print('url')
    return render_template('show_data.html',url=url)

@app.route('/', methods=['GET','POST'])
def home():
    return render_template('login.html')





# -------------路由定位页面-------------

if __name__ == '__main__':
    app.run()